/**
 * @version	1.0.0
 *   Change Log:
 *    - 0.6.0: Original Version : SeYoung Jang
 *    - 0.6.1: Updated Widget management for Android : JJ Kim
 *    - 0.6.2: Updated Widget management for Android : JJ Kim
 *    - 0.6.3: Fixed some bugs on Widget management for Android : JJ Kim
 *    - 0.6.4: Fixed some bugs on Widget management for iPhone : Seyoung
 *    - 0.6.5: Updated Widget management for Android : JJ Kim
 *    - 0.6.6: Small BlackBerry Update : Bart
 *    - 0.6.7: Version Management : Seyoung
 *    - 1.0.0: release
 * */

var array = new Array();

function Widget() {
	this.id = null;
	this.name = null;
	this.icon = null;
	this.version = null;
	this.vendor = null;
	this.description = null;
	this.categoryId = null;
	this.categoryName = null; 
	this.installDate = null;
	this.updateDate = null;
	this.available = false;
	this.state = null;
	this.price = null;
}

/**
 * Wiget Life-Cycle Manager. Start, Exit, Install, Update, Delete 
 * @author	SeYoung Jang
 */
function WidgetManager() {
	this.widgetServer = "http://203.235.212.103/simulator";
	this.currentWidgetId = null;
	this.widgets = new Array();
	this.widgetsOnStore = new Array();
	this.widgetRootPath = "";
	
	this.successCallback = null;
	this.errorCallback = null;
	this.renderStatusFlag = false;
	
	if(device.platformName == "Android")
		this.widgetRootPath = widgetManagerD.getWidgetRootPath();
	
	this.xmlHandler = new SKTXmlHandler();
}

/**
 * Init Widget list and widget count.
 * Must be called at initPage();
 */
WidgetManager.prototype.initWidgetManager = function() {
	if(device.platformName == "Android")
		widgetManagerD.initWidgetManager();
	else if(device.platformName == "BlackBerry")
		widgetManagerD.initWidgetManager();
	else if(device.platformName == "iPhone") {
	}
};

/**
 * Gets all installed widgets.
 * @return {Array}	Returns installed widget list.
 */
WidgetManager.prototype.getWidgetList = function() {
	if(device.platformName == "Android")
		widgetManagerD.getWidgetList();
	else if(device.platformName == "BlackBerry")
		widgetManagerD.getWidgetList();
	else if(device.platformName == "iPhone")
		AlopexGap.exec("WidgetManager.getWidgetList");
};

/**
 * Gets installed widget count.
 * @return {int}	Returns installed widget count. 
 */
WidgetManager.prototype.getWidgetCount = function() {
	if(device.platformName == "Android" || device.platformName == "BlackBerry")
		return widgetManagerD.getWidgetCount();
	else if(device.platformName == "iPhone") {
		if(this.widgets != "undefined") {
			return this.widgets.length;
		} else {
			return 0;
		}
	}
};

/**
 * Starts widget with widgetId
 * @param {String} widgetId
 * @return {Array}	Returns widget list.
 */
WidgetManager.prototype.startWidget = function(widgetId) {
	if(device.platformName == "Android" || device.platformName == "BlackBerry")
		widgetManagerD.startWidget(widgetId);
	else if(device.platformName == "iPhone") {
		AlopexGap.exec("WidgetManager.startWidget", widgetId);
	}
};

/**
 * Gets widgets list in store.
 * @param {String} searchQuery 		
 * @param {String} category		
 * @param {String} page 		
 * @return {Array}	Returns widget list.
 */
WidgetManager.prototype.getStoreWidgetList = function(searchQuery, category, page) {
	var params = new Object();
	
	if(device.platformName == "Android") {
		params["primitive"] = "CMS_LIST_Android";
		params["function"] = "CMS_LIST_Android";
	}
	else if(device.platformName == "BlackBerry") {
		params["primitive"] = "CMS_LIST_BlackBerry";
		params["function"] = "CMS_LIST_BlackBerry";
	}
	else if(device.platformName == "iPhone") {
		params["primitive"] = "CMS_LIST_iPhone";
		params["function"] = "CMS_LIST_iPhone";
	}
	
	if(searchQuery != null && searchQuery != undefined && searchQuery != "")
		params["searchQuery"] = searchQuery;
	if(category != null && category != undefined && category != "")
		params["category"] = category;
	if(page != null && page != undefined && page != "")
		params["page"] = page;
	
	var xmlStr = this.xmlHandler.make(params);
	
	http.requestPostBody(this.widgetServer, xmlStr, storeWidgetListSuccessCallback, widgetManagerFailCallback);
};


WidgetManager.prototype.getStoreWidget = function(aWidgetId, aSuccessCallback, aErrorCallback) {
	if(aWidgetId == null) return;
	
	self.successCallback = aSuccessCallback;
	self.errorCallback = aErrorCallback;
	
	var params = new Object();
	params["primitive"] = "CMS_" + aWidgetId.toUpperCase() + "_CONTENT_"  + device.platformName;
	params["function"] = "CMS_" + aWidgetId.toUpperCase() + "_CONTENT_"  + device.platformName;
	
	var xmlStr = this.xmlHandler.make(params);
	
	http.requestPostBody(this.widgetServer, xmlStr, storeWidgetSuccessCallback, widgetManagerFailCallback);
};

/**
 * Gets my widget list in server.
 * @param {String} page 
 * @return {Array} Returns widget list in server history.  		
 */
WidgetManager.prototype.getServerWidgetList = function(page) {
	if(device.platformName == "Android") {
	}
	else if(device.platformName == "BlackBerry") {
		return widgetManagerD.getServerWidgetList(page);
	}
	else if(device.platformName == "iPhone") {
	}
};

/**
 * Install widget.
 * @param {String} widgetId
 * @param {Function} progress callback function. callbackName(widgetId, progress); 
 * @param {Function} success callback function. callbackName(widgetId); 
 * @param {Function} errir callback function. callbackName(widgetId); 
 * @return {Array} Returns widget list in server history.  		
 */
WidgetManager.prototype.installWidget = function(widgetId, downloadUrl) {
	if(device.platformName == "Android")
		widgetManagerD.installWidget(widgetId, downloadUrl);
	else if(device.platformName == "BlackBerry") {
		widgetManagerD.installWidget(widgetId, progressCallback, successCallback, errorCallback);
	}
	else if(device.platformName == "iPhone") {
		AlopexGap.exec("WidgetManager.installWidget", widgetId, downloadUrl);
	}
};

/**
 * Update widget.
 * @param {String} widgetId
 * @param {Function} progress callback function. callbackName(widgetId, progress); 
 * @param {Function} success callback function. callbackName(widgetId); 
 * @param {Function} errir callback function. callbackName(widgetId); 
 * @return {Array} Returns widget list in server history.  		
 */
WidgetManager.prototype.updateWidget = function(widgetId, downloadUrl) {
	if(device.platformName == "Android")
		widgetManagerD.updateWidget(widgetId, downloadUrl);
	else if(device.platformName == "BlackBerry") {
		widgetManagerD.updateWidget(widgetId, progressCallback, successCallback, errorCallback);
	}
	else if(device.platformName == "iPhone") {
		AlopexGap.exec("WidgetManager.updateWidget", widgetId, downloadUrl);
	}
};

/**
 * Delete widget.
 * @param {String} widgetId
 * @param {Function} progress callback function. callbackName(widgetId, progress); 
 * @param {Function} success callback function. callbackName(widgetId); 
 * @param {Function} errir callback function. callbackName(widgetId); 
 * @return {Array} Returns widget list in server history.  		
 */
WidgetManager.prototype.deleteWidget = function(widgetId) {
	if(device.platformName == "Android")
		widgetManagerD.deleteWidget(widgetId);
	else if(device.platformName == "BlackBerry")
		widgetManagerD.deleteWidget(widgetId);
	else if(device.platformName == "iPhone") {
		AlopexGap.exec("WidgetManager.deleteWidget", widgetId);
	}
};

var widgetManager;

AlopexGap.addConstructor(function() {
	if(typeof widgetManager == "undefined")
		widgetManager = new WidgetManager();
});

function storeWidgetListSuccessCallback() {
	nativeUI.dismissProgressDialog();
	
	var xmlStr = http.response;
	var result = parseXml(xmlStr, "result");
	
	if(result != "1000") {
		alert(parseXml(xmlStr, "resultMessage"));
		
		return;
	}
	
	dataSet = widgetManager.xmlHandler.parse(xmlStr);
	var widgets = dataSet.getList("cmsList");
	list.setData(widgets);
	
	for(var i = 0; i < widgets.length; i++)
		widgetManager.widgetsOnStore.push(mapToWidget(widgets[i]));
	
	renderList();
	
	widgetManager.renderStatusFlag = true;
	widgetManager.getWidgetList();
	
	scroll1.refresh();
};

function widgetManagerFailCallback() {
	nativeUI.dismissProgressDialog();
	log.error(http.error);
//	if(self.errorCallback != null) this.errorCallback();
}

function storeWidgetSuccessCallback() {
	var xmlStr = http.response;
	var result = parseXml(xmlStr, "result");
	
	if(result != "1000") {
		alert(parseXml(xmlStr, "resultMessage"));
		
		return;
	}
	
	var dataSet = widgetManager.xmlHandler.parse(xmlStr);
	
	if(this.successCallback != null && this.successCallback != "undefined") {
		this.successCallback(dataSet);
	}
}

function installSuccessCallback(widgetId) {
	alert(widgetId + " widget was installed successfully");
	if(executeButton != null && executeButton != "undefined")
		executeButton.setDisplay("none");
}

function installFailCallback(widgetId) {
	alert("Fail to install " + widgetId + " widget");
}

function updateSuccessCallback(widgetId) {
	alert(widgetId + " widget was updated successfully");
	if(executeButton != null && executeButton != "undefined")
		executeButton.setDisplay("none");
}

function updateFailCallback(widgetId) {
	alert("Fail to update " + widgetId + " widget");
}

function getListWidgetCallback() {
	var array = new Array();
	var map;
	
	if(widgetManager.renderStatusFlag)
		renderListStatus();
	else {
		for(var i = 0; i < widgetManager.widgets.length; i++) {
			map = new Map();
			map.put("id", widgetManager.widgets[i].id);
			map.put("image", widgetManager.widgets[i].icon);
			map.put("title", widgetManager.widgets[i].name);
			map.put("version", widgetManager.widgets[i].version);
			array.push(map);
		}
		
		list.setData(array);
		renderListForMyApps();
	}
}

function parseXml(xmlStr, tagName) {
	var xml = (new DOMParser()).parseFromString(xmlStr, "text/xml");
	
	return xml.getElementsByTagName(tagName)[0].firstChild.nodeValue;
}

function mapToWidget(map) {
	var widget = new Widget();
	
	widget.id = map.get("appId");
	widget.name = map.get("appName");
	widget.icon = map.get("imageUrl");
	widget.version = map.get("version");
	widget.description = map.get("appDesc");
	widget.updateDate = map.get("updateDate");
	widget.state = map.get("state");
	widget.price = map.get("price");
	widget.available = true;
	
	return widget;
}

function renderList() {
	var size = list.element.getElementsByTagName("li").length;
	
	for(var i = 0; i < size; i++) {
		var element = list.getItemAt(i).getElementsByTagName("div")[0];
		element.style.backgroundImage = "url(" + element.innerHTML + ")";
		element.innerHTML = "";
		
		var data = list.getData();
		
		if(data[i].get("state") == "Null") {
			list.getItemAt(i).getElementsByTagName("div")[4].innerHTML = data[i].get("price");
			list.getItemAt(i).getElementsByTagName("div")[4].style.color = "#FFF98E";
		}
		
		if(list.getItemAt(i).getElementsByTagName("div")[4].innerHTML == "Update")
			list.getItemAt(i).getElementsByTagName("div")[4].style.color = "orange";
	}
}

function renderListForMyApps() {
	var size = list.element.getElementsByTagName("li").length;
	
	for(var i = 0; i < size; i++) {
		var element = list.getItemAt(i).getElementsByTagName("div")[0];
		var id = list.getData()[i].get("id");
		
		element.style.background = "url(" + widgetManager.widgetRootPath + "/" + id + "/res/image" + element.innerHTML + ") no-repeat center center";
		element.innerHTML = "";
	}
}

function renderListStatus() {
	var size = list.element.getElementsByTagName("li").length;
	
	var data = list.getData();
	var status;
	
	for(var i = 0; i < size; i++) {
		status = "null";
		for(var j = 0; j < widgetManager.widgets.length; j++) {
			if(data[i].get("appId") == widgetManager.widgets[j]["id"]) {
				status = "Installed";
				if(data[i].get("version") > widgetManager.widgets[j]["version"]) {
					status = "Update";
				}
			}
		}
		
		data[i].put("state", status);
		
		if(status == "Installed") {
			list.getItemAt(i).getElementsByTagName("div")[4].innerHTML = "Installed";
		} else if(status == "Update") {
			list.getItemAt(i).getElementsByTagName("div")[4].innerHTML = "Update";
			list.getItemAt(i).getElementsByTagName("div")[4].style.color = "orange";
		} else {
			list.getItemAt(i).getElementsByTagName("div")[4].innerHTML = data[i].get("price");
			list.getItemAt(i).getElementsByTagName("div")[4].style.color = "#FFF98E";
		}
	}
}

/**
 * Widget Container Main Layout
 * @inherits Layout (alopex_ui.js)
 * @return
 */
function WidgetContainer() {
	this.base = Layout;
	this.base();
	this.widgets = null;
}

/**
 * Sets widgets in container grid and dynamically html elements.
 * @param {Array} widgetList Widget object array 
 */
WidgetContainer.prototype.setWidgets = function(widgetList) {
	carousel = new Carousel3D("coverflow");
	carouselClickHandler = [];
	
	this.widgets = widgetList;
	
	var size = widgetList.length;
	
	for(var i = 0; i < size; i++)
		this.addWidgetAtIndex(widgetList[i], i);
	
	carousel.setOnCarouselClickHandler(onCarouselClick);
	list.setData(array);
	list.setOnItemClickHandler(onListItemClickHandler);
	renderListForMyApps();
};

function onCarouselClick(index) {
	carouselClickHandler[index]();
}

function onListItemClickHandler(e) {
	var target = e.currentTarget;
	
	carouselClickHandler[target.index]();
}

/**
 * Adds widget at index in container grid.
 * @param {Widget} widget 
 */
WidgetContainer.prototype.addWidgetAtIndex= function(widget, index) {
	var widgetList = document.getElementById("widgetList");
	var widgets = widgetList.getElementsByTagName("li");
	var widgetElement = widgets.item(index);
	var iconElement = widgetElement.getElementsByTagName("div").item(0);
	
	iconElement.style.background = "url(" + widgetManager.widgetRootPath + "/" + widget.id + "/res/image" + widget.icon + ") no-repeat center center";
	iconElement.onclick = function(e) { widgetManager.startWidget(widget.id); };
	carouselClickHandler[index] = function(e) { widgetManager.startWidget(widget.id); };
	
	var titleElement = widgetElement.getElementsByTagName("div").item(1);
	titleElement.innerHTML = widget.name;
	
	carousel.addCoverImage(widgetManager.widgetRootPath + "/" + widget.id + "/res/image/icon/large_icon.png");
	
	var map;
	
	map = new Map();
	map.put("id", widgetManager.widgets[index].id);
	map.put("image", widgetManager.widgets[index].icon);
	map.put("title", widgetManager.widgets[index].name);
	map.put("version", widgetManager.widgets[index].version);
	array.push(map);
};

/**
 * Adds widget at the end in container grid.
 * @param {Widget} widget 
 */
WidgetContainer.prototype.addWidget = function(widget) {
};

/**
 * Removes widget at index in container grid.
 * @param {Widget} widget 
 */
WidgetContainer.prototype.removeWidgetAtIndex= function(widget, index) {
};

/**
 * Removes widget at the end in container grid.
 * @param {Widget} widget 
 */
WidgetContainer.prototype.removeWidget = function(widget) {
};